package com.example.springbootmpdemo.controller;


import com.example.springbootmpdemo.entity.Member;
import com.example.springbootmpdemo.entity.Team;
import com.example.springbootmpdemo.service.IMemberService;
import com.example.springbootmpdemo.service.ITeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author metasequoia
 * @since 2021-12-19
 */
@Controller
@RequestMapping("/team")
public class TeamController {
    @Autowired
    private IMemberService iMemberService;

    @Autowired
    private ITeamService iTeamService;

    @PostMapping("/create")
    public ModelAndView createTeam(@RequestParam int memberid,
                                  @RequestParam String password,
                                  @RequestParam String name){
        //根据memberid获取member对象
        Member member = iMemberService.getById(memberid);
        //若为空则显示不存在
        if(member==null){
            ModelAndView mv = new ModelAndView("teamError");
            //直接一个字符串，也可以“取名”
            mv.addObject("error","该成员ID不存在！");
            mv.addObject("member",member);
            return mv;
        }


        if(!member.getPassword().equals(password)){
            ModelAndView mv = new ModelAndView("teamError");
            mv.addObject("error","成员密码错误！");
            mv.addObject("member",member);
            return mv;
        }

        Team team = new Team();
        team.setLeaderid(memberid);
        team.setName(name);

        //等一下，teamid是自增长的，怎么能获取并修改相应member中的teamid的值呢？
        //也许此时已经有值了，不妨一试！——此时并没有值，但至少填上这两句不会报错！没有任何效果罢了


        if(iTeamService.save(team)){
            //save执行完之后，team即获得了自动生成的teamid
            //同步更新领队成员的member记录里的teamid信息
            member.setTeamid(team.getTeamid());
            iMemberService.updateById(member);

            ModelAndView mv = new ModelAndView("teamSuccess");
            mv.addObject("team",team);
            //把member对象也传过去，为了创建队伍后还可以带值返回个人页
            mv.addObject("member",member);
            return mv;
        }else{
            ModelAndView mv = new ModelAndView("teamError");
            mv.addObject("error","一般来说你不会见到这个错误的，要错就直接globelError了");
            return mv;
        }


    }

    @PostMapping("/searchAll")
    public ModelAndView searchAll(@RequestParam int memberid){
        Member member = iMemberService.getById(memberid);

        List<Team> teamList = iTeamService.list();

        ModelAndView mv = new ModelAndView("teamSearch");
        mv.addObject("member",member);
        mv.addObject("teamList",teamList);

        return mv;
    }

}
